﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.WeixinMP.Models;
using Microhard.WeixinMP.Interfaces;
using System.Configuration;
using System.Xml.Linq;
using Microhard.Core;
using System.Reflection;
using System.Diagnostics;

namespace Microhard.WeixinMP.Impls
{
    public class WeixinBaseController : Controller
    {
        private IWeixinMP wx = new HandshakeImpl();
        protected List<IWeixinRobotResponse> _allRp = new List<IWeixinRobotResponse>();

        public WeixinBaseController()
        {
            //添加欢迎处理类
            _allRp.Add(new WelcomeCommandImpl());
            _allRp.Add(new SubscribeMe());
            _allRp.Add(new StaticMsgSender());
            _allRp.Add(new FeedbackWXHandler());
            _allRp.Add(new WXArticleResponse());
            _allRp.Add(new WXAskResponer());
            _allRp.Add(new WXAlert());

        }


        /// <summary>
        /// 获得系统定义好的自动回复接口
        /// </summary>
        /// <returns></returns>
        protected virtual void GetAllResponses()
        {
            return;
        }

        /// <summary>
        /// 供微信平台调用
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult CheckSignature(string signature, string timestamp, string nonce, string echostr)
        {
            WeixinHandshakeModel whm = new WeixinHandshakeModel();
            whm.signature = signature;
            whm.timestamp = timestamp;
            whm.nonce = nonce;
            whm.token = ConfigurationManager.AppSettings["weixinToken"];
            if (wx.Handshake(whm))
            {
                return Content(echostr);
            }
            return Content("非微信接口调用");
        }

        [HttpPost]
        [ActionName("Index")]
        public virtual ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            Log.Info("RunInfo", "----记录开始----");
            //初始化回复类
            this.GetAllResponses();

            WeixinHandshakeModel whm = new WeixinHandshakeModel();
            whm.signature = signature;
            whm.timestamp = timestamp;
            whm.nonce = nonce;
            whm.token = ConfigurationManager.AppSettings["weixinToken"];
            if (!wx.Handshake(whm))
            {
                Log.Error("WeixinBaseController.Post", "微信会话检测失败");
                return Content("微信会话检测失败");
            }
            WeixinBaseData<object> response = new WeixinBaseData<object>();
            try
            {
                var xd = XDocument.Load(this.Request.InputStream);

                Log.Info("RunInfo", "消息明细:" + xd.ToString());

                #region  debug
                //                string xml = "<xml>" +
                //"<ToUserName><![CDATA[toUser]]></ToUserName>" +
                //"<FromUserName><![CDATA[FromUser]]></FromUserName>" +
                //"<CreateTime>123456789</CreateTime>" +
                //"<MsgType><![CDATA[event]]></MsgType>" +
                //"<Event><![CDATA[CLICK]]></Event>" +
                //"<EventKey><![CDATA[dd23d7fe-76da-4918-8db6-663769df0abb_yyr]]></EventKey>" +
                //"</xml>";



                //                var xd = XDocument.Parse(xml);
                #endregion

                string msgType = xd.Element("xml").Element("MsgType").Value;
                string fromusername = xd.Element("xml").Element("FromUserName").Value;
                RequestServiceModel request = new RequestServiceModel();
                request.XDocument = xd;
                request.WeixinContext = this.HttpContext;
                request.MsgType = msgType;
                request.WXMPAccountUser = this.HttpContext.Items["MPAccountUser"] as WXMPAccountModel;
                //添加附加公司信息


                IWeixinRobotResponse irr = null;
                switch (msgType)
                {
                    case "text":
                        WeixinBaseData<WeixinTxt> text = new WeixinBaseData<WeixinTxt>(xd);
                        request.Txt = text.ToModel();
                        request.MsgCreateTime = text.CreateTime;
                        request.MsgId = text.MsgId;
                        irr = ResponseFactory.GetResponseByTxtRequest(request, _allRp);
                        break;
                    case "location":
                        WeixinBaseData<WeixinLocation> location = new WeixinBaseData<WeixinLocation>(xd);
                        request.Location = location.ToModel();
                        request.MsgCreateTime = location.CreateTime;
                        request.MsgId = location.MsgId;
                        break;
                    case "link":
                        WeixinBaseData<WeixinLink> link = new WeixinBaseData<WeixinLink>(xd);
                        request.Link = link.ToModel();
                        request.MsgCreateTime = link.CreateTime;
                        request.MsgId = link.MsgId;
                        break;
                    case "image":
                        WeixinBaseData<WeixinImage> image = new WeixinBaseData<WeixinImage>(xd);
                        request.Image = image.ToModel();
                        request.MsgCreateTime = image.CreateTime;
                        request.MsgId = image.MsgId;
                        break;
                    case "event":
                        WeixinBaseData<WeixinEvent> wevent = new WeixinBaseData<WeixinEvent>(xd);
                        request.Event = wevent.ToModel();
                        request.MsgCreateTime = wevent.CreateTime;
                        request.MsgId = wevent.MsgId;
                        //使用event key判断菜单事件
                        irr = ResponseFactory.GetResponseByEventKey(request, _allRp);
                        break;
                    default:
                        Log.Error("不可识别的微信信息类型", xd.ToString());
                        break;
                }
                if (irr == null)
                {
                    irr = ResponseFactory.GetResponseByType(request.MsgType, _allRp);
                }
                this.HttpContext.Items["wxmsg"] = request;

                //根据输入的指令进行对话
                response = irr.GetResponse(request); ;
            }
            catch (Exception ex)
            {
                Log.Error("微信接受错误", ex);
            }
            string xmlForPost = response.ToString();

            watch.Stop();
            Log.Info("RunInfo", "发送处理时间(毫秒):" + watch.ElapsedMilliseconds);
            Log.Info("RunInfo", "回复内容:" + xmlForPost);
            Log.Info("RunInfo", "----执行完毕---");
            this.Response.ContentType = "text/xml";
            return Content(xmlForPost);
        }
    }
}
